package com.yhy.dubbo.service.mongo;

import com.yhy.domain.mongo.Visitors;
import com.yhy.domain.vo.PageResult;
import com.yhy.dubbo.api.mongo.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Visitors> topVisitors(Long userId, Long created, Integer i) {
        Criteria criteria = Criteria
                .where("userId").is(userId)
                .and("date").gt(created);

        Query query = new Query(criteria).limit(i);

        return mongoTemplate.find(query,Visitors.class);
    }

    //获取所有访问者的id的集合
    @Override
    public PageResult queryVisitorsList(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);

        long count = mongoTemplate.count(new Query(criteria), Visitors.class);

        Query query = new Query(criteria).skip((page-1)*pagesize).limit(pagesize);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            userIds.add(visitors.getVisitorUserId());
        }
        return new PageResult(page,pagesize, (int) count,userIds);
    }
}